package org.japo.java.jdbc.samples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.japo.java.entities.EnlaceBD;

/**
 *
 * @author José A. Pacheco Ondoño - joanpaon@gmail.com
 */
public class DlgEnlaceBD extends javax.swing.JDialog {

    // Entidad de enlazado del dialogo
    private EnlaceBD enlace = new EnlaceBD();
    
    // Conexión con la base de datos
    private Connection conexion;

    // Propiedades de la conexión
    private Properties propConexion;

    public DlgEnlaceBD(java.awt.Frame parent, boolean modal) {
        // Establece la ejecución modal del diálogo
        super(parent, modal);

        // Inicialización anterior a la construcción del interfaz
        iniciarAnterior();

        // Construir el interfaz gráfico
        initComponents();

        // Inicialización posterior a la construcción del interfaz
        iniciarPosterior();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        lblTipo = new javax.swing.JLabel();
        cbbTipo = new javax.swing.JComboBox();
        lblBD = new javax.swing.JLabel();
        txfBD = new javax.swing.JTextField();
        lblServidor = new javax.swing.JLabel();
        txfServidor = new javax.swing.JTextField();
        lblPuerto = new javax.swing.JLabel();
        ftfPuerto = new javax.swing.JFormattedTextField();
        lblUsuario = new javax.swing.JLabel();
        txfUserBD = new javax.swing.JTextField();
        lblPassword = new javax.swing.JLabel();
        pwfPassBD = new javax.swing.JPasswordField();
        btnConDes = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblTipo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblTipo.setText("Tipo");

        cbbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No definido", "Access", "MySQL" }));

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${enlace.tipo}"), cbbTipo, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cbbTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbbTipoActionPerformed(evt);
            }
        });

        lblBD.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblBD.setText("Base de datos");

        txfBD.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${enlace.bd}"), txfBD, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        lblServidor.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblServidor.setText("Servidor");

        txfServidor.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${enlace.servidor}"), txfServidor, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        lblPuerto.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblPuerto.setText("Puerto");

        ftfPuerto.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${enlace.puerto}"), ftfPuerto, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        lblUsuario.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblUsuario.setText("Usuario");

        txfUserBD.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${enlace.user}"), txfUserBD, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        lblPassword.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblPassword.setText("Contraseña");

        pwfPassBD.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${enlace.pass}"), pwfPassBD, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        btnConDes.setText("Conectar");
        btnConDes.setEnabled(false);
        btnConDes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConDesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnConDes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblTipo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbbTipo, 0, 210, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblBD)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txfBD))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblServidor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txfServidor))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblPuerto)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ftfPuerto))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblUsuario)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txfUserBD))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pwfPassBD)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lblBD, lblPassword, lblPuerto, lblServidor, lblTipo, lblUsuario});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTipo)
                    .addComponent(cbbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblBD)
                    .addComponent(txfBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblServidor)
                    .addComponent(txfServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPuerto)
                    .addComponent(ftfPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUsuario)
                    .addComponent(txfUserBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPassword)
                    .addComponent(pwfPassBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnConDes)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lblBD, lblPassword, lblPuerto, lblServidor, lblTipo, lblUsuario});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {cbbTipo, ftfPuerto, txfBD, txfServidor, txfUserBD});

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cbbTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbbTipoActionPerformed
        actualizarInterfaz();
    }//GEN-LAST:event_cbbTipoActionPerformed

    private void btnConDesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConDesActionPerformed
        // Determina el estado de la conexión
        if (btnConDes.getText().equals("Conectar")) {
            // Conecta la base de datos
            conectarBD();

            // Oculta el diálogo de conexión
            setVisible(false);
        } else {
            // Desconecta la base de datos
        }
    }//GEN-LAST:event_btnConDesActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DlgEnlaceBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DlgEnlaceBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DlgEnlaceBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DlgEnlaceBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                DlgEnlaceBD dialog = new DlgEnlaceBD(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConDes;
    private javax.swing.JComboBox cbbTipo;
    private javax.swing.JFormattedTextField ftfPuerto;
    private javax.swing.JLabel lblBD;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblPuerto;
    private javax.swing.JLabel lblServidor;
    private javax.swing.JLabel lblTipo;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPasswordField pwfPassBD;
    private javax.swing.JTextField txfBD;
    private javax.swing.JTextField txfServidor;
    private javax.swing.JTextField txfUserBD;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private void iniciarPosterior() {
        actualizarInterfaz();
    }

    private void actualizarInterfaz() {
        // Actualizar datos interfaz
        actualizarModelo();

        // Actualizar botones
        actualizarControles();
    }

    /**
     * Método: actualizarModelo Este método actualiza los parámetros de conexión
     * actuales en función del tipo de base de datos seleccionada. Los valores
     * de referencia son cogidos de las propiedades de conexión cargadas en la
     * construcción del diálogo.
     */
    private void actualizarModelo() {
        // Analiza el tipo seleccionado
        switch (enlace.getTipo()) {
            case "Access":
                enlace.setBd(propConexion.getProperty("bd"));
                enlace.setServidor("");
                enlace.setPuerto("");
                enlace.setUser("");
                enlace.setPass("");
                break;
            case "MySQL":
                enlace.setBd(propConexion.getProperty("bd"));
                enlace.setServidor(propConexion.getProperty("servidor"));
                enlace.setPuerto(propConexion.getProperty("puerto"));
                enlace.setUser(propConexion.getProperty("user"));
                enlace.setPass(propConexion.getProperty("pass"));
                break;
            default:
                enlace.setBd("");
                enlace.setServidor("");
                enlace.setPuerto("");
                enlace.setUser("");
                enlace.setPass("");
                break;
        }
    }

    /**
     * Método: actualizarControles Este método actualiza el estado de los
     * controles en función del tipo de base de datos seleccionada.
     */
    private void actualizarControles() {
        // Obtiene el tipo de BD seleccionado
        String tipo = getEnlace().getTipo();

        // Analiza el tipo seleccionado
        switch (tipo) {
            case "Access":
                txfBD.setEnabled(true);
                txfServidor.setEnabled(false);
                ftfPuerto.setEnabled(false);
                txfUserBD.setEnabled(false);
                pwfPassBD.setEnabled(false);
                btnConDes.setEnabled(true);
                break;
            case "MySQL":
                txfBD.setEnabled(true);
                txfServidor.setEnabled(true);
                ftfPuerto.setEnabled(true);
                txfUserBD.setEnabled(true);
                pwfPassBD.setEnabled(true);
                btnConDes.setEnabled(true);
                break;
            default:
                txfBD.setEnabled(false);
                txfServidor.setEnabled(false);
                ftfPuerto.setEnabled(false);
                txfUserBD.setEnabled(false);
                pwfPassBD.setEnabled(false);
                btnConDes.setEnabled(false);
                break;
        }
    }

    public EnlaceBD getEnlace() {
        return enlace;
    }

    public void setEnlace(EnlaceBD enlace) {
        this.enlace = enlace;
    }
    
    public Connection getConexion() {
        return conexion;
    }

    public void setConexion(Connection conexion) {
        this.conexion = conexion;
    }

    /**
     * Metodo conectarBD
     * Conecta con la base de base de datos seleccionada y actualiza el 
     * atributo "conexion" con la referencia a dicha conexión.
     * Para añadir un nuevo tipo de base de datos hay que agregar una nueva
     * opcion "case" con el identificativo del nuevo tipo y crear un nuevo
     * metodo del tipo conectarXXX(bd) donde se resuelva las condiciones
     * de la nueva conexión
     */
    public void conectarBD() {
        // Tipo de base de datos
        String tipoBD = propConexion.getProperty("tipo");

        // Proceso de conexión
        try {
            // Conecta con la base de datos
            switch (tipoBD) {
                case "Access":
                    conectarAccess();
                    break;
                case "MySQL":
                    conectarMySQL();
                    break;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private void conectarMySQL() throws Exception {
        // Parámetros de la conexión
        String bd = enlace.getBd();
        String protocolo = enlace.getProtocolo();
        String servidor = enlace.getServidor();
        String puerto = enlace.getPuerto();
        String user = enlace.getUser();
        String pass = enlace.getPass();

        // Cadena de conexión de MySQL
        final String CADENA_CONEXION = ""
                + protocolo + "://"
                + servidor + ":"
                + puerto + "/"
                + bd;

        // Realiza la conexión
        conexion = DriverManager.getConnection(CADENA_CONEXION, user, pass);
    }

    private void conectarAccess() throws Exception {
        // Parámetros de la conexión
        String bd = enlace.getBd();
        String protocolo = enlace.getProtocolo();
        
        // Cadena de conexión de Access
        final String CADENA_CONEXION = protocolo + ":" + bd;

        // Realiza la conexión
        conexion = DriverManager.getConnection(CADENA_CONEXION);
    }

    private void iniciarAnterior() {
        // Instancia la entidad de enlazado
        enlace = new EnlaceBD();

        // Obtiene una referencia a las propiedades de conexión
        propConexion = enlace.getPropConexion();
    }
}
